package com.petshop.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.petshop.mapper.AdminMapper;
import com.petshop.pojo.Admin;
import com.petshop.pojo.Orders;
import com.petshop.service.AdminService;
import com.petshop.utils.JwtHelper;
import com.petshop.utils.MD5Util;
import com.petshop.utils.Result;
import com.petshop.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 20289
 * @description 针对表【admin(管理员信息表)】的数据库操作Service实现
 * @createDate 2025-02-27 11:17:00
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
        implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JwtHelper jwtHelper;

    /**
     * 管理员登录
     *
     * @param admin
     * @return
     */
    @Override
    public Result login(Admin admin) {
        LambdaQueryWrapper<Admin> lambdaQueryWrapper =
                new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getUsername, admin.getUsername());
        Admin loginAdmin = adminMapper.selectOne(lambdaQueryWrapper);
        //判断账号是否正确
        if (loginAdmin == null) {
            return Result.build(null, ResultCodeEnum.USERNAME_ERROR);
        }
        //账号正确，判断密码是否正确
        if (!StringUtils.isEmpty(admin.getPassword()) &&
                MD5Util.encrypt(admin.getPassword()).equals(loginAdmin.getPassword())) {
            //密码正确，登录成功。根据用户地id生成token，将token封装到result并返回
            String token = jwtHelper.createToken(Long.valueOf(loginAdmin.getAdminId()));
            return Result.ok(token);
        }
        return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
    }

    /**
     * 管理员注册
     *
     * @param admin
     * @return
     */
    @Override
    public Result regist(Admin admin) {
        //检查账号是否被注册
        LambdaQueryWrapper<Admin> lambdaQueryWrapper =
                new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getUsername, admin.getUsername());
        Long count = adminMapper.selectCount(lambdaQueryWrapper);
        if (count > 0) {
            return Result.build(null, ResultCodeEnum.USERNAME_USED);
        }
        //密码加密
        admin.setPassword(MD5Util.encrypt(admin.getPassword()));
        adminMapper.insert(admin);
        return Result.ok(null);
    }


}




